package com.demo.pdf.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@Service
public class PdfFillService {

    private static final Logger logger = LoggerFactory.getLogger(PdfFillService.class);

    /**
     * 填充PDF表单字段
     *
     * @param templatePath PDF模板文件路径
     * @param fieldValues  要填充的字段值映射
     * @return 填充后的PDF字节数组
     * @throws IOException IO异常
     */
    public byte[] fillPdfForm(String templatePath, Map<String, String> fieldValues) throws IOException {
        try (PDDocument document = PDDocument.load(new File(templatePath))) {
            PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
            
            if (acroForm == null) {
                throw new IOException("该PDF文件不包含可填写的表单");
            }

            // 填充表单字段
            for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
                PDField field = acroForm.getField(entry.getKey());
                if (field != null) {
                    field.setValue(entry.getValue());
                } else {
                    logger.warn("未找到字段: {}", entry.getKey());
                }
            }

            // 必须调用flatten()方法以使填写的内容可见
            acroForm.flatten();
            
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            return baos.toByteArray();
        }
    }

    /**
     * 创建简单的文本PDF（无表单字段）
     *
     * @param content 要写入PDF的内容
     * @return PDF字节数组
     * @throws IOException IO异常
     */
    public byte[] createSimpleTextPdf(String content) throws IOException {
        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                contentStream.beginText();
                contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
                contentStream.newLineAtOffset(50, 750);
                contentStream.showText(content);
                contentStream.endText();
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            return baos.toByteArray();
        }
    }

    /**
     * 在现有PDF的指定位置添加文本
     *
     * @param templatePath PDF模板文件路径
     * @param text         要添加的文本
     * @param x            X坐标
     * @param y            Y坐标
     * @return 添加文本后的PDF字节数组
     * @throws IOException IO异常
     */
    public byte[] addTextToPdf(String templatePath, String text, float x, float y) throws IOException {
        try (PDDocument document = PDDocument.load(new File(templatePath))) {
            PDPage page = document.getPage(0); // 获取第一页
            
            try (PDPageContentStream contentStream = new PDPageContentStream(document, page, 
                    PDPageContentStream.AppendMode.APPEND, true)) {
                contentStream.beginText();
                contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
                contentStream.newLineAtOffset(x, y);
                contentStream.showText(text);
                contentStream.endText();
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            return baos.toByteArray();
        }
    }
}